<template>
  <div class="pic-box">
    <el-upload
      action="https://jsonplaceholder.typicode.com/posts/"
      list-type="picture-card"
      :file-list="images"
      :on-preview="handlePreview"
      :before-remove="beforeRemove"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="visible">
      <img width="100%" :src="previewImg" />
    </el-dialog>
  </div>
</template>

<script type='text/ecmascript-6'>
export default {
  name: "pic",
  props: {
    images: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      previewImg: "",
      visible: false,
    }
  },
  methods: {
    beforeRemove(file, fileList) {
      return new Promise((resolve, reject) => {
        this.$confirm(`是否删除该图片？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({ type: 'success', message: '删除成功!' })
          resolve()
          return true
        }).catch(err => {
          reject(err)
          return false
        })
      })
    },
    handleRemove(file, fileList) {
      const type = "remove"
      const o = { file, fileList, type }
      this._upload(o)
    },
    handlePreview(file) {
      this.previewImg = file.url
      this.visible = true
    },
    handleSuccess(response, file, fileList) {
      const type = "success"
      const o = { file, fileList, type }
      this._upload(o)
    },
    _upload(o) {
      this.$emit("upload-change", o)
    }
  },
}
</script>